package com.woniuxy.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.entity.IpLocationInfo;
import com.woniuxy.service.IpLocationService;
import jakarta.servlet.http.HttpServletRequest;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Service
public class IpLocationServiceImpl implements IpLocationService {
    private final OkHttpClient httpClient;
    private final ObjectMapper objectMapper;

    // 使用IP-API服务获取地理位置信息
    private static final String IP_API_URL = "http://ip-api.com/json/%s";

    public IpLocationServiceImpl(OkHttpClient httpClient, ObjectMapper objectMapper) {
        this.httpClient = httpClient;
        this.objectMapper = objectMapper;
    }

    /**
     * 根据IP地址获取地理位置信息
     * @param ip IP地址
     * @return 地理位置信息
     */
    @Override
    public IpLocationInfo getLocationByIp(String ip) {
        // 构建API请求URL
        String url = String.format(IP_API_URL, ip);

        // 创建HTTP请求
        Request request = new Request.Builder()
                .url(url)
                .build();

        // 执行请求并处理异常
        try (Response response = httpClient.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected response code: " + response);
            }

            // 解析JSON响应
            String json = response.body().string();
            Map<String, Object> result = objectMapper.readValue(json, HashMap.class);

            // 检查API状态
            if (!"success".equals(result.get("status"))) {
                throw new IOException("IP location lookup failed: " + result.get("message"));
            }

            // 映射结果到模型对象
            return mapToLocationInfo(result);
        } catch (IOException e) {
            // 转换为运行时异常，避免违反方法签名
            throw new RuntimeException("Failed to get location information for IP: " + ip, e);
        }
    }

    /**
     * 从API响应映射到位置信息对象
     */
    private IpLocationInfo mapToLocationInfo(Map<String, Object> result) {
        IpLocationInfo info = new IpLocationInfo();
        info.setIp((String) result.get("query"));
        info.setCountry((String) result.get("country"));
        info.setRegionName((String) result.get("regionName"));
        info.setCity((String) result.get("city"));
        info.setZip((String) result.get("zip"));
        info.setLat((Double) result.get("lat"));
        info.setLon((Double) result.get("lon"));
        info.setTimezone((String) result.get("timezone"));
        info.setIsp((String) result.get("isp"));
        info.setOrg((String) result.get("org"));
        info.setAs((String) result.get("as"));
        return info;
    }

    /**
     * 从HTTP请求中获取客户端IP地址
     */
    @Override
    public String getClientIp(HttpServletRequest request) {
        String xffHeader = request.getHeader("X-Forwarded-For");
        if (xffHeader == null) {
            return request.getRemoteAddr();
        }
        // 处理多级代理的情况，取第一个IP
        return xffHeader.split(",")[0].trim();
    }
}